import { insertDom, imageLoad } from './util.js'
import NodeManager from './NodeManager.js'
import LineManager from './LineManager.js'
import BranchManager from './BranchManager.js'
import './snow.css'

class Snow {
    constructor(container, option) {
        this.container = container
        this.option = option
        this.imgList = [
            { src: '../image/2.4G_Left.png', name: 'image2GLeft' },
            { src: '../image/2.4G_Right.png', name: 'image2GRight' },
            { src: '../image/5G_Left.png', name: 'image5GLeft' },
            { src: '../image/5G_Right.png', name: 'image5GRight' }
        ]
        this.imageList = {}
        this.initImage()
        imageLoad(this.imageList, () => {
            this.init(option.data, container)
        })
    }

    initImage() {
        this.imgList.forEach((item, index) => {
            this.imageList[item.name] = new Image()
            this.imageList[item.name].src = item.src
        })
    }

    init(data) {
        data.forEach((dataItem, index) => {
            new BranchManager(dataItem, this.container, this.option, this.imageList)
        })
        // const warpper = insertDom(this.container, { className: 'sc-container' })
        // data.length && data.forEach((item, index) => {
        //     this.initCenter(warpper, item)
        // })
    }

    // 插入中心dom
    initCenter(warpper, data) {
        this.centerNode = new NodeManager(warpper, data, this.option)
        this.centerNode.init()
        const NodeRtnWrapper = this.centerNode.returnWrapper()
        this.initContent(data, NodeRtnWrapper)
        if (data.children && data.children.length > 0) {
            // 创建圆周节点集合
            const nodeGroup = insertDom(warpper, { className: 'sc-child-group' })
            // 创建连线节点集合
            const lineGroup = insertDom(warpper, { className: 'sc-line-group' })
            imageLoad(this.imageList, () => {
                data.children.forEach((child, index) => {
                    // 插入圆周dom
                    const deg = 360 / data.children.length * index
                    this.initChildDom(child, nodeGroup, deg)
                    this.initLine(child, lineGroup, deg, index)
                })
            })
        }
    }

    initChildDom(data, nodeGroup, deg) {
        this.childNode = new NodeManager(nodeGroup, data, this.option, deg)
        this.childNode.init(false)
        // 暴露给用户render的容器
        const NodeRtnWrapper = this.childNode.returnWrapper()
        this.initContent(data, NodeRtnWrapper)
    }

    initLine(data, lineGroup, deg, index) {
        new LineManager(lineGroup, data, this.option, deg, this.imageList, index)
    }

    // 自定义render
    initContent(data, NodeRtnWrapper) {
        const renderFun = data.render || this.option.render
        if (renderFun) {
            renderFun(NodeRtnWrapper, data)
            this.centerNode.setAngle()
            this.childNode?.setAngle()
        }
    }
}

export default Snow